package com.plugin.sproutcore.ui.events;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class EventDispatcher
{
	private final Map<EventType, List<IEventListener>> _listeners = new HashMap<EventType, List<IEventListener>>(0);
	
	private final List<IEventListener> _getListeners(EventType eventType) 
	{
		List<IEventListener> listeners = _listeners.get(eventType);
		if (listeners == null) {
			listeners = new ArrayList<IEventListener>();
			_listeners.put(eventType, listeners);
		}
		return listeners;
	}
	
	protected final synchronized void addListener( EventType eventType, IEventListener l ) 
    {
    	_getListeners(eventType).add( l );
    }
    
    protected final synchronized void removeListener( EventType eventType, IEventListener l ) 
    {
    	_getListeners(eventType).remove( l );
    }
     
    protected final synchronized void dispatchEvent( EventType eventType, EventObject event ) 
    {
    	Iterator<IEventListener> listeners = _getListeners(eventType).iterator();
    	while (listeners.hasNext() )
    	{
    		listeners.next().handleEvent(eventType, event);
    	}
    }
}
